#include "touchitem.h"
#include <QPainter>
#include <QGraphicsSceneMouseEvent>

TouchItem::TouchItem(int x, int y, QString title)
{
    this->x = x;
    this->y = y;
    this->title = title;
    commonAlpha = 127;
    clickedAlpha = 200;
    setZValue(1);
    QPixmap * pixmap = new QPixmap(40, 40);
    pixmap->fill(QColor(0, 0, 255, commonAlpha));
    QPainter painter(pixmap);
    painter.setPen(QPen(Qt::white));
    painter.setRenderHint(QPainter::Antialiasing, true);
    painter.setFont(QFont("Arial", 18, 1));
    painter.drawText(18, 25, title);
    commonPixmap = QSharedPointer<QPixmap>(pixmap);
    curPixmap = pixmap;

    pixmap = new QPixmap(40, 40);
    pixmap->fill(QColor(0, 0, 255, clickedAlpha));
    QPainter painter2(pixmap);
    painter2.setPen(QPen(Qt::white));
    painter2.setRenderHint(QPainter::Antialiasing, true);
    painter2.setFont(QFont("Arial", 18, 1));
    painter2.drawText(18, 25, title);
    clickedPixmap = QSharedPointer<QPixmap>(pixmap);
    setPixmap(*curPixmap);
}

TouchItem::~TouchItem()
{}

QRectF TouchItem::boundingRect() const
{
    return QRectF(0, 0, 40, 40);
}

QPainterPath TouchItem::shape() const
{
    QPainterPath path;
    path.addRect(boundingRect());
    return path;
}

void TouchItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
//    qDebug("pressed touch item");
    curPixmap = clickedPixmap.data();
    setPixmap(*curPixmap);
    event->accept();
    update(boundingRect());
}

void TouchItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
//    qDebug("moved touch item");
    if((event->buttons() & Qt::LeftButton) && boundingRect().contains(event->pos())) {
        if(curPixmap != clickedPixmap.data()) {
            curPixmap = clickedPixmap.data();
            setPixmap(*curPixmap);
        }
    } else {
        if(curPixmap != commonPixmap.data()) {
            curPixmap = commonPixmap.data();
            setPixmap(*curPixmap);
        }
    }
    event->accept();
}

void TouchItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
//    qDebug("released touch item");
    if(curPixmap != commonPixmap.data()) {
        curPixmap = commonPixmap.data();
        setPixmap(*curPixmap);
    }
    event->accept();
    if(boundingRect().contains(event->pos()))
        emit clicked();
}
